﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Collections;
using System.Diagnostics;
using System.Text.RegularExpressions;


namespace task_runner
{

	class PrjProperty
	{
		public static string Version = "ver 1.2012.03.05";
		/// <summary>
		/// Путь к серверу
		/// </summary>
		public static string ServerPath;
		/// <summary>
		/// Путь к серверу .arc
		/// </summary>
		public static string ServerPathArc;
		/// <summary>
		/// Путь к клиенту
		/// </summary>
		public static string LocalPath;
		/// <summary>
		///  Имя клиента
		/// </summary>
		public static string ClientName;

		/// <summary>
		/// Список файлов-задач
		/// </summary>
		public static List<string> FilesTaskList;

		/// <summary>
		/// Список задач
		/// </summary>
		public static List<Task> TaskList;

		/// <summary>
		/// Log-лист
		/// </summary>
		public static List<string> Logs;

		/// <summary>
		/// Список параметров
		/// </summary>
		public static List<Param> Params;

		#region Init() -- Инициализация параметров
		public static void Init()
		{
			Logs = new List<string>();
			FilesTaskList = new List<string>();
			TaskList = new List<Task>();
			Params = new List<Param>();
		}
		#endregion Init

		#region LoadConfig LoadXMLrun(string filename) -- Чтение файла xml
		/// <summary>
		/// Чтение файла xml
		/// </summary>
		/// <param name="filename">имя файла</param>
		public static void LoadConfig(string filename)
		{
			string spath = "";

			spath = PrjProperty.LocalPath + "\\";
			XmlTextReader reader = new XmlTextReader(spath + filename);
			bool isXMLconfig = false;
			bool isXMLparams = false;

			#region while (reader.Read())
			while (reader.Read())
			{
				#region XmlNodeType.Element
				if (reader.NodeType == XmlNodeType.Element) //Если элемент 
				{
					#region task-runner
					if (reader.Name == "task-runner")
					{
						isXMLconfig = true;
					}
					#endregion task-runner
					#region server
					if (isXMLconfig && reader.Name == "server")
					{
						PrjProperty.ServerPath = reader.GetAttribute("path");
						PrjProperty.ServerPathArc = PrjProperty.ServerPath + "\\.arc";
					}
					#endregion server
					#region client
					if (isXMLconfig && reader.Name == "client")
					{
						PrjProperty.ClientName = reader.GetAttribute("name");
					}
					#endregion client
					#region default-param
					if (isXMLconfig && reader.Name == "default-param")
					{
						isXMLparams = true;
					}
					#region param
					if (isXMLconfig && isXMLparams && reader.Name == "param")
					{
						isXMLparams = true;
						PrjProperty.Params.Add(new Param()
						{
							Name = reader.GetAttribute("name"),
							Value = reader.GetAttribute("value")
						});
					}
					#endregion param
					#endregion default-param
				}
				#endregion XmlNodeType.Element

				#region XmlNodeType.EndElement
				if (reader.NodeType == XmlNodeType.EndElement) //Если элемент 
				{
					#region task-runner
					if (reader.Name == "task-runner")
					{
						isXMLconfig = false;
					}
					#endregion task-runner
					#region default-param
					if (isXMLconfig && reader.Name == "default-param")
					{
						isXMLparams = false;
					}
					#endregion default-param

				}
				#endregion XmlNodeType.EndElement
			}
			#endregion while (reader.Read())
			reader.Close();
		}
		#endregion LoadConfig

		#region LoadXMLrun(string filename) -- Чтение файла xml
		/// <summary>
		/// Чтение файла xml
		/// </summary>
		/// <param name="filename">имя файла</param>
		public static void LoadXMLrun(string filename)
		{
			Logs.Add("Открытие " + filename);
			XmlTextReader reader = new XmlTextReader(filename);
			bool isXMLtaskrunner = false;
			bool isXMLcommand = false;
			bool isXMLrun = false;
			Task task = new Task();

			DateTime commandDate = DateTime.Today;
			#region while (reader.Read())
			while (reader.Read())
			{
				#region XmlNodeType.Element
				if (reader.NodeType == XmlNodeType.Element) //Если элемент 
				{
					#region task-runner
					if (reader.Name == "task-runner")
					{
						isXMLtaskrunner = true;
					}
					#endregion task-runner
					#region command
					if (isXMLtaskrunner && reader.Name == "command")
					{
						isXMLcommand = true;
						string sdate = reader.GetAttribute("startdate");
						string stime = reader.GetAttribute("starttime");
						task = new Task();
						task.FileName = filename;
						commandDate = Convert.ToDateTime(sdate + " " + stime);
						task.Name = "Task " + commandDate.ToString();
						task.DateStart = commandDate;
						PrjProperty.TaskList.Add(task);
					}
					#endregion command
					#region run
					if (isXMLtaskrunner && isXMLcommand && reader.Name == "run")
					{
						isXMLrun = true;
						task.DateStart = commandDate;
						int taskListCount = PrjProperty.TaskList.Count - 1;
						PrjProperty.TaskList[taskListCount].Commands.Add(new TskCommand() { TypeCmd = "run" });
					}
					#endregion run
					#region copy
					if (isXMLtaskrunner && isXMLcommand && reader.Name == "copy")
					{
						isXMLcommand = true;
						string scopyfrom = reader.GetAttribute("copyfrom");
						string scopyto = reader.GetAttribute("copyto");
						string isparam = reader.GetAttribute("isparam");
						int taskListCount = PrjProperty.TaskList.Count - 1;
						TskCommand tskcommand = new TskCommand { TypeCmd = "copy" };
						tskcommand.Params.Add(new Param() { Name = "FileName", Value = scopyfrom });
						tskcommand.Params.Add(new Param() { Name = "CopyToPath", Value = scopyto });
						tskcommand.Params.Add(new Param() { Name = "ParamIsUseParam", Value = isparam });
						PrjProperty.TaskList[taskListCount].Commands.Add(tskcommand);
					}
					#endregion copy
					#region change-param
					if (isXMLtaskrunner && isXMLcommand && reader.Name == "change-param")
					{
						isXMLcommand = true;
						string sname = reader.GetAttribute("name");
						string svalue = reader.GetAttribute("value");

						int taskListCount = PrjProperty.TaskList.Count - 1;
						TskCommand tskcommand = new TskCommand { TypeCmd = "change-param" };
						tskcommand.Params.Add(new Param() { Name = "Name", Value = sname });
						tskcommand.Params.Add(new Param() { Name = "Value", Value = svalue });
						PrjProperty.TaskList[taskListCount].Commands.Add(tskcommand);

					}
					#endregion change-param
					#region update
					if (isXMLtaskrunner && isXMLcommand && reader.Name == "update")
					{
						isXMLcommand = true;
						string sfile = reader.GetAttribute("file");

						int taskListCount = PrjProperty.TaskList.Count - 1;
						TskCommand tskcommand = new TskCommand { TypeCmd = "update" };
						tskcommand.Params.Add(new Param() { Name = "file", Value = sfile });
						PrjProperty.TaskList[taskListCount].Commands.Add(tskcommand);
					}
					#endregion update
				}
				#endregion XmlNodeType.Element

				#region XmlNodeType.Text
				if (reader.NodeType == XmlNodeType.Text) //Если Text 
				{
					if (isXMLtaskrunner && isXMLcommand && isXMLrun)
					{
						int taskListCount = PrjProperty.TaskList.Count - 1;
						int commandCount = PrjProperty.TaskList[taskListCount].Commands.Count - 1;
						PrjProperty.TaskList[taskListCount].Commands[commandCount].Params.Add(new Param() { Name = "FileName", Value = reader.Value });
					}
				}
				#endregion XmlNodeType.Text

				#region XmlNodeType.EndElement
				if (reader.NodeType == XmlNodeType.EndElement) //Если элемент 
				{
					#region task-runner
					if (reader.Name == "task-runner")
					{
						isXMLtaskrunner = false;
					}
					#endregion task-runner
					#region command
					if (reader.Name == "command")
					{
						isXMLcommand = false;
						int taskListCount = PrjProperty.TaskList.Count - 1;
						//listBox1.Items.Add(PrjProperty.TaskList[taskListCount].Name);
					}
					#endregion command
					#region run
					if (reader.Name == "run")
					{
						isXMLrun = false;
						int taskListCount = PrjProperty.TaskList.Count - 1;
						int commandCount = PrjProperty.TaskList[taskListCount].Commands.Count - 1;
						//listBox1.Items.Add(PrjProperty.TaskList[taskListCount].Command[commandCount].Command);
					}
					#endregion run
				}
				#endregion XmlNodeType.EndElement
			}
			#endregion while (reader.Read())
			reader.Close();
		}
		#endregion LoadXMLrun

		#region SaveXMLParam (string filename) -- Запись файла xml
		/// <summary>
		/// Запись файла xml
		/// </summary>
		/// <param name="filename">имя файла</param>
		public static void SaveXMLParam(string filename)
		{
			XmlTextWriter writer = new XmlTextWriter(PrjProperty.LocalPath + "\\" + filename, System.Text.Encoding.Default);
			writer.Formatting = Formatting.Indented;
			writer.WriteStartDocument();
			writer.WriteComment("Created by task-runner ver." + Version);
			writer.WriteComment("Date: " + DateTime.Now.ToString());
			writer.WriteStartElement("task-runner");
			writer.WriteStartElement("default-param");
			foreach (Param param in Params)
			{
				writer.WriteStartElement("param");
				writer.WriteAttributeString("name", param.Name);
				writer.WriteAttributeString("value", param.Value);
				writer.WriteEndElement();//param
			}

			writer.WriteEndElement();//default-param
			writer.WriteEndElement();//task-runner
			writer.WriteEndDocument();
			writer.Close();

		}
		#endregion SaveXMLParam

		#region string GetParam(string sName) -- Поиск значения параметра
		/// <summary>
		/// Поиск значения параметра
		/// </summary>
		/// <param name="sName">Имя параметра</param>
		/// <returns>Значения параметра</returns>
		public static string GetParam(string sName)
		{
			string ret = null;
			foreach (Param prm in Params)
			{
				ret = "";
				if (prm.Name.ToLower() == sName.ToLower())
					ret = prm.Value;
			}
			return ret;
		}
		#endregion GetParam

		#region RunTaskAll() -- Выполнение команд в задаче
		/// <summary>
		/// Выполнение команд в задаче
		/// </summary>
		public static void RunTaskAll()
		{
			foreach (Task task in TaskList)
			{
				if (task.DateStart < DateTime.Now && task.Name != "del")
				{
					PrjProperty.Logs.Add("Выполнение " + task.Name);
					string res = task.RunCommandAll();
					string strfname = Path.GetFileName(task.FileName);
					File.Move(task.FileName, PrjProperty.ServerPathArc + "\\" + strfname);
					task.Name = "del";
					if (res.ToLower() == "exit;")
					{
						Environment.Exit(0);
					}
				}
			}
		}
		#endregion RunTaskAll()
	}
}